<template>
	<view>
		<!-- 企业用车登录 -->

		<view class="purpose_login">
			<view class="login_icon">
				<image src="@/bundle2/static/purpose_icon.png" mode="widthFix"></image>
			</view>
			<view class="title">
				<view class="txt">
					欢迎使用
				</view>
				<view class="txt">
					粤顺行平台
				</view>
			</view>

			<view class="login_form">
				<!--  -->
				<view class="input_box ">
					<view class="tit">
						账号
					</view>
					<view class="input_area FlexAlign " :class="{ 'isfocus': isf_phone }">
						<view class="icon_box FlexRow">
							<i class="iconfont icon-a-lujing13"></i>
						</view>
						<input v-model.trim="account" type="number" class="FlexItem" @focus="isf_phone = true"
							@blur="isf_phone = false" placeholder="请输入账号" placeholder-class="myplaceholder">
					</view>
				</view>
				<!--  -->
				<view class="input_box">
					<view class="tit">
						密码
					</view>

					<view class="input_area FlexAlign" :class="{ 'isfocus': isf_pwass }">
						<view class="icon_box FlexRow">
							<i class="iconfont icon-passw"></i>
						</view>

						<input type="password" v-model.trim="password" @focus="isf_pwass = true"
							@blur="isf_pwass = false" class="FlexItem" placeholder="请输入密码"
							placeholder-class="myplaceholder">


						<router-link class="forgetpass FlexAlign" to="/bundle2/pages/forget_pwd/forget_pwd">
							{{ $zhTran('忘记密码') }}
						</router-link>

					</view>
				</view>

				<view class="defconfirm_btn gradient_bg4" @click="$u.throttle(loginFun, 2000)">
					登录
				</view>

				<view class="register">
					<router-link class="lighter" to="/bundle2/pages/register/register" v-if="isPhoneRegister">
						{{ $zhTran('注册账号') }}
					</router-link>
				</view>

				<view class="thirdParty">


					<!-- #ifdef MP-WEIXIN -->
					<view v-if="isMnpWxAuth">
						<view class="quick_login gradient_bg4 FlexRow" @tap="mnpLogin">
							{{ $zhTran('手机号快捷登录')}}
						</view>
					</view>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<view v-if="isOaWxAuth && isWeixin">
						<view class="quick_login gradient_bg4 FlexRow" @tap="getCodeUrl">
							{{ $zhTran('手机号快捷登录')}}
						</view>
					</view>
					<!-- #endif -->

				</view>

				<view class="agreement FlexRow" @click="explan_checked = !explan_checked">
					<view class="check_box FlexRow" :class="{ 'isCheck': explan_checked }">
						<i class="iconfont icon-duihao"></i>
					</view>
					<text>
						已阅读并同意
					</text>
					<view class="agrepup" @click.stop="lookServe">
						<router-link data-theme="" to="/bundle/pages/server_explan/server_explan?type=1">
							{{ $zhTran('《服务协议》') }}
						</router-link>
					</view>
					<text>
						和
					</text>
					<view class="agrepup" @click.stop="lookServe">
						<router-link to="/bundle/pages/server_explan/server_explan?type=2">
							{{ $zhTran('《隐私协议》') }}
						</router-link>
					</view>
				</view>


			</view>
		</view>

		<!-- #ifdef MP-WEIXIN -->
		<mplogin-popup v-model="showLoginPop" :logo="appConfig.logo" :title="appConfig.shop_name"
			:login-data="loginData" @close="closePopup" @update="handleSubmitInfo" />
		<!--  #endif -->

		<u-popup mode="center" length="86%" v-model="multiShow">
			<view class="multi-popup p-30">
				<view class="flex row-center font-size-40">{{ $zhTran('选择用户') }}</view>
				<view class="multi-info m-t-20" v-for="item, idx in relevanceList" :key="idx">
					<view class="flex row-between p-20" @click="toLogin(idx, item)">
						<view class="avatar m-r-20">
							<u-image width="100rpx" height="100rpx" border-radius="10%" :src="item.user.avatar" />
						</view>
						<view class="info">
							<view class="name flex row-between">
								<text>{{ item.user.nickname }}</text>
								<view class="flex">
									<view class="m-l-30 m-r-10">
										<u-image width="30rpx" height="30rpx" :src="$getImageUri(item.level_img)" />
									</view>
									<text>{{ item.level }}</text>
								</view>
							</view>
							<view class="m-t-20 flex row-between">
								<text style="color: rgba(169, 169, 169, 1);">{{ item.user.mobile }}</text>
								<view class="flex" v-if="item.is_used">
									<view class="circle"></view>
									<text>{{ $zhTran('上次登录') }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>


<script>
	import {
		mapMutations,
		mapActions,
		mapGetters
	} from "vuex";
	import {
		apiAuthLogin,
		apiAccountLogin,
		apiLoginCaptcha,
		apiToutiaoAuthLogin,
		apiAppWxLogin,
		apiUpdateUser,
	} from "@/api/app";
	import wechath5 from "@/utils/wechath5";
	import {
		isWeixinClient,
		currentPage,
		client,
		trottle
	} from "@/utils/tools";
	import Cache from "@/utils/cache";
	import {
		BACK_URL,
		INVITE_CODE,
		TOKEN,
	} from "@/config/cachekey";
	import {
		getCode,
		getUserProfile
	} from "@/utils/login";
	import {
		apiRelevanceList,
		apiLoginUser
	} from "@/api/user_multi_switch"
	import {
		apiLogout, //退出登录
	} from "@/api/user";
	const loginType = {
		ACCOUNT: 1,
		SMS_CODE: 2,
	};
	export default {
		data() {
			return {
				password: "",
				account: "",
				code: "",
				loginType: "",
				isWeixin: "",
				codeTips: "",
				showLoginPop: false,
				loginData: {},
				options: {},
				multiShow: false,
				relevanceList: [],
				explan_checked: false,

				isf_pwass: false,
				isf_phone: false,


			};
		},

		methods: {
			lookServe() {

			},
			// 
			...mapMutations(["login"]),
			...mapActions(["getUser"]),
			// 小程序微信登录
			async mnpLogin() {
				if (!this.explan_checked) {
					this.$toast({
						title: this.$zhTran("请阅读并同意《服务协议》《隐私协议》")
					});
					return;
				}
				const {
					userInfo: {
						avatarUrl,
						nickName,
						gender
					},
				} = await getUserProfile();
				uni.showLoading({
					title: this.$zhTran("登录中..."),
					mask: true,
				});
				const wxCode = await getCode();
				const data = await apiAuthLogin({
					code: wxCode,
					nickname: nickName,
					headimgurl: avatarUrl,
				});

				// uni.setStorageSync('UserInfos', JSON.stringify(data))

				if (data.is_new_user) {
					uni.hideLoading();
					this.showLoginPop = true;
					this.loginData = data;
				} else {
					this.loginHandle(data);
				}
				// this.loginHandle(data)
			},
			getCodeUrl() {
				wechath5.getWxUrl();
			},
			// 公众号微信登录
			async oaLogin(code) {
				if (!code) return;
				const data = await wechath5.authLogin(code);
				this.loginHandle(data);
			},
			oaAutoLogin() {
				// H5微信登录
				const {
					code
				} = this.$Route.query;
				this.isWeixin = isWeixinClient();
				if (this.isLogin) {
					// 已经登录 => 首页
					uni.switchTab({
						url: "/pages/index/index",
					});
					return;
				}
				if (code) {
					// 带有code => 登录
					return this.oaLogin(code);
				}
				if (this.isWeixin && this.isOaWxAutoLogin) {
					// 开启自动授权登录
					this.getCodeUrl();
				}
			},
			// app微信登录
			async appLogin() {
				if (!this.explan_checked) {
					this.$toast({
						title: this.$zhTran("请阅读并同意《服务协议》《隐私协议》")
					});
					return;
				}
				uni.login({
					provider: "weixin",
					success: (res) => {
						uni.showLoading({
							title: this.$zhTran("登录中..."),
							mask: true,
						});
						const {
							openid,
							access_token
						} = res.authResult;
						apiAppWxLogin({
								openid,
								access_token,
							})
							.then((res) => {
								this.loginHandle(res);
							})
							.finally((res) => {
								uni.hideLoading();
							});
					},
				});
			},
			// 账号登录
			async loginFun() {
				console.log('loginFun')
				const {
					account,
					password,
					telephone,
					code,
					loginType
				} = this;
				if (!account) {
					this.$toast({
						title: this.$zhTran("请输入手机号"),
					});
					return;
				}

				if (this.loginType == 1 && !password) {
					this.$toast({
						title: this.$zhTran("请输入密码"),
					});
					return;
				}
				if (this.loginType == 2 && !code) {
					this.$toast({
						title: this.$zhTran("请输入验证码"),
					});
					return;
				}

				if (!this.explan_checked) {
					this.$toast({
						title: this.$zhTran("请阅读并同意《服务协议》《隐私协议》")
					});
					return;
				}

				apiAccountLogin({
					scene: 1,
					account,
					password,
					code: "",
				}).then((res) => {
					this.loginHandle(res);
				});
			},
			// 登录结果处理
			async loginHandle(data) {

				await this.login(data);
				this.getUser();
				// 更新购物车
				this.$store.dispatch("getCartNum");

				uni.hideLoading();

				if (this.userInfo.user_multi_switch && !this.multiShow && this.relevanceList.length != 1) {
					apiRelevanceList()
						.then((res) => {
							this.relevanceList = res
							if (res.length == 1) {
								this.loginHandle(data);
							} else {
								this.multiShow = true
							}
						})
				} else {
					if (this.isBindMobile && !data.mobile) {
						return this.$Router.replace({
							path: "/bundle2/pages/bind_mobile/bind_mobile",
							query: {
								...this.options
							}

						});
					}
					this.goBack();
				}
			},
			toLogin(idx, row) {
				var idx_used = this.relevanceList.findIndex((item) => {
					return item.is_used == 1
				})
				apiLogout().then((res) => {
					apiLoginUser({
						user_id: row.user_id
					}).then((res) => {
						this.loginHandle(res);
					})
				});
			},
			goBack() {

				const {
					share_id,
					poster_type,
					poster_level,
					clsp_id
				} = this.options
				if (poster_type) {
					if (poster_type == 1) {
						this.$Router.push({
							path: '/bundle2/pages/community_group_purchase/leader/leader_center',
							query: {
								share_id
							}
						})
					} else {
						this.$Router.push({
							path: '/bundle2/pages/level_apply/apply',
							query: {
								share_id,
								poster_level
							}
						})
					}
				} else if (Cache.get('cloud_shop_enabled')) {
					this.$Router.push({
						path: `/bundle2/pages/cloud_shop/diyshop/index`,
						query: {
							clspId: clsp_id
						}

					})
				} else {
					if (getCurrentPages().length > 1) {
						// console.log(TOKEN + '000', Cache.get(TOKEN))
						this.$Router.back(1, {
							success: () => {
								const {
									onLoad,
									options
								} = currentPage();
								// 刷新上一个页面
								onLoad && onLoad(options);
							},
						});
					} else if (Cache.get(BACK_URL)) {
						this.$Router.replace(Cache.get(BACK_URL));
					} else {
						this.$Router.replaceAll("/pages/index/index");
					}
				}
				Cache.remove(BACK_URL);
			},
			changeLoginType() {
				if (this.loginType == loginType.ACCOUNT) {
					this.loginType = loginType.SMS_CODE;
				} else if (this.loginType == loginType.SMS_CODE) {
					this.loginType = loginType.ACCOUNT;
				}
			},
			// 发送验证码
			sendSMS() {
				if (!this.$refs.uCode.canGetCode) return;
				if (!this.account) {
					this.$toast({
						title: this.$zhTran("请输入手机号"),
					});
					return;
				}
				apiLoginCaptcha({
					mobile: this.account,
				}).then((res) => {
					this.$refs.uCode.start();
				});
			},

			codeChange(tip) {
				this.codeTips = tip;
			},
			// 头条小程序登录
			async ttLogin() {
				if (!this.explan_checked) {
					this.$toast({
						title: this.$zhTran("请阅读并同意《服务协议》《隐私协议》")
					});
					return;
				}
				const code = await getCode();
				const [err, res] = await uni.getUserInfo();
				if (!res) {
					this.openSetting();
					return;
				}
				const {
					avatarUrl,
					nickName
				} = res.userInfo;
				uni.showLoading({
					title: this.$zhTran("登录中..."),
				});

				apiToutiaoAuthLogin({
						code,
						avatarUrl,
						nickName,
					})
					.then((res) => {
						this.loginHandle(res);
					})
					.catch((res) => {
						console.log(res);
						uni.hideLoading();
					});
			},
			openSetting() {
				uni.showModal({
					title: this.$zhTran("温馨提示"),
					content: this.$zhTran("您已拒绝授权，是否前往设置打开个人信息授权？"),
					confirmColor: this.themeColor,
					success(res) {
						if (res.confirm) {
							uni.openSetting();
						}
					},
				});
			},
			async handleSubmitInfo(e) {
				const loginData = this.loginData
				const res = await apiUpdateUser(e, loginData.token);
				this.loginHandle(loginData);
			},
			closePopup() {
				this.showLoginPop = false;
			},
		},
		computed: {
			// 开启手机号注册
			isPhoneRegister() {
				const {
					register_way
				} = this.appConfig;
				if (!register_way) {
					return false;
				}
				return register_way.some((item) => item == 1);
			},
			// 开启强制绑定手机号
			isBindMobile() {
				const {
					coerce_mobile
				} = this.appConfig;
				return coerce_mobile;
			},
			// 登录方式数组
			loginWay() {
				const {
					login_way
				} = this.appConfig;
				if (!login_way) return false;
				this.loginType = login_way[0] || "";
				return login_way;
			},
			// 是否包含对应的登录方式
			hasLoginWay() {
				return (type) => {
					return this.loginWay && this.loginWay.some((item) => item == type);
				};
			},
			// 开启小程序微信授权
			isMnpWxAuth() {
				const {
					mnp_wechat_auth
				} = this.appConfig;
				return mnp_wechat_auth;
			},

			// 开启小程序微信授权
			isOaWxAuth() {
				const {
					h5_wechat_auth
				} = this.appConfig;
				return h5_wechat_auth;
			},
			// 开启app微信授权
			isAPPWxAuth() {
				const {
					app_wechat_auth
				} = this.appConfig;
				return app_wechat_auth;
			},
			// 开启公众号微信自动登录
			isOaWxAutoLogin() {
				const {
					h5_auto_wechat_auth
				} = this.appConfig;
				return h5_auto_wechat_auth;
			},
			// 开启小程序头条登录
			isToutiaoAuth() {
				const {
					toutiao_auth
				} = this.appConfig;
				return toutiao_auth;
			},
		},
		onLoad() {
			uni.clearStorage();
			uni.clearStorageSync()
			// if (__wxConfig.envVersion === 'develop') {
			// 	this.develop_flag = true
			// }
			if (this.$Route.meta.atitle) {
				uni.setNavigationBarTitle({
					title: this.$zhTran(this.$Route.meta.atitle)
				})
			}

			this.options = this.$Route.query
			this.mnpLogin = trottle(this.mnpLogin);
			this.appLogin = trottle(this.appLogin);
			this.getCodeUrl = trottle(this.getCodeUrl);
			this.ttLogin = trottle(this.ttLogin);
			// #ifdef H5
			this.oaAutoLogin();
			// #endif
		},
		onUnload() {},
	};
</script>

<style scoped lang="scss">
	@import "@/bundle4/css/Flex.scss";

	page {
		background: #E9F7F7 !important;
	}

	.agreement {
		width: 100%;
		margin-top: 30rpx;
		// position: fixed;
		// bottom: 0;
		// left: 0;
		z-index: 20;

		// padding-bottom: 50rpx;
		.check_box {

			width: 24rpx;
			height: 24rpx;
			border-radius: 100%;
			border: 2rpx solid rgba(204, 204, 204, 1);
			background: #fff;

			i {
				color: #fff;
				font-size: 20rpx;
			}

			&.isCheck {
				background: $uniThemeColor;
				border-color: $uniThemeColor;
			}
		}

		text {
			margin: 0 5rpx 0 9rpx;
			font-size: 22rpx;
			font-weight: 400;
			color: rgba(153, 153, 153, 1);
		}

		.agrepup {
			font-size: 22rpx;
			font-weight: 400;
			color: $uniThemeColor;
		}
	}


	.register {

		font-size: 28rpx;
		font-weight: 400;
		color: rgba(153, 153, 153, 1);
		text-align: right;
		vertical-align: top;
		margin-top: 24rpx;

	}

	.thirdParty {
		width: 100%;
		margin-top: 40rpx;

		.title {
			font-size: 24rpx;
			font-weight: 400;
			color: rgba(52, 57, 101, 0.5);
			text-align: center;
			vertical-align: top;


			&::after,
			&::before {
				content: '';
				display: inline-block;
				width: 210rpx;
				height: 2rpx;
				opacity: 0.2;
				background: #979AB2;
			}

			&::after {
				margin-left: 20rpx;
			}

			&::before {
				margin-right: 20rpx;
			}
		}

		.login_icon {
			margin: 0 auto;
			margin-top: 20rpx;
			width: 136rpx;
			height: 136rpx;
			border-radius: 100%;
			background: #FFFFFF;
			box-shadow: 0rpx 0rpx 100rpx rgba(55, 62, 125, 0.06);

			i {
				color: #4AD574;
				font-size: 45rpx;
			}
		}

		.quick_login {
			margin: 0 auto;
			margin-top: 20rpx;
			width: 240rpx;
			height: 70rpx;
			border-radius: 40rpx;
		}
	}

	.defconfirm_btn {
		margin-top: 40rpx;
		// box-shadow: 0rpx 0rpx 40rpx rgba(64, 115, 250, 0.2);
		box-shadow: 0rpx 0rpx 40rpx rgba(6, 120, 120, 0.2);


	}

	.purpose_login {
		padding: 60rpx 66rpx 20rpx 66rpx;

		background: #E9F7F7;
		width: 100%;
		min-height: calc(100vh - env(safe-area-inset-bottom));

		.login_icon {
			image {
				width: 104rpx;
				height: 105rpx;
			}
		}

		.title {
			margin: 35rpx 0;

			.txt {
				font-size: 46rpx;
				font-weight: 550;
				color: rgba(52, 57, 101, 1);
			}
		}
	}


	.input_box:last-of-type {
		margin-bottom: 142rpx;
	}

	.input_box {
		width: 100%;
		margin-bottom: 40rpx;

		.tit {
			margin-bottom: 16rpx;
			font-size: 32rpx;
			font-weight: 400;
			color: rgba(52, 57, 101, 1);
		}

		.input_area.isfocus {
			border: solid 1px $uniThemeColor;

			.myplaceholder {
				color: #343965 !important;
			}
		}

		.input_area {
			border: 1px solid transparent;
			transition: all .3s;
			width: 100%;
			border-radius: 12rpx;
			overflow: hidden;
			height: 100rpx;
			background: #fff;
			position: relative;

			.icon_box {
				// padding-left: 30rpx;
				width: 100rpx;
				height: 100%;

				// bordeR:solid 1px red;
				i {
					color: $uniThemeColor;
					font-size: 40rpx;
				}
			}

			input {
				padding-right: 26rpx;
				color: $uniThemeColor;
				font-size: 28rpx;
				background: none !important;
				outline: none;
				border: none !important;
			}

			.myplaceholder {
				font-size: 28rpx;
				color: #343965;
			}

			.forgetpass {
				font-size: 28rpx;
				font-weight: 400;
				color: rgba(102, 102, 102, 1);
				text-align: left;
				padding-right: 26rpx;

				&::before {
					content: '';
					display: inline-block;
					width: 1px;
					height: 16px;
					margin-right: 24rpx;
					background: rgba(0, 0, 0, .24);
				}
			}


		}


	}
</style>